<!--
  * 对账司机提成
  *
-->
<template>
  <!---------- 查询表单form begin ----------->
  <a-card size="small" :bordered="false" :hoverable="false" class="query-form-wrapper smart-margin-bottom10 smart-radius-2">
    <a-form>
      <a-row :gutter="[8, 10]">
        <a-col :span="5.5">
          <a-form-item label="单据日期" class="smart-margin-bottom0">
            <custom-range-picker v-model:value="queryForm.create_time" />
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item label="司机" class="smart-margin-bottom0">
            <Select name="Driver" v-model:value="queryForm.driver_id" placeholder="司机" allow-clear @input-enter="onSearch" />
          </a-form-item>
        </a-col>
        <a-col :span="5">
          <a-button-group>
            <a-button type="primary" html-type="submit" @click="onSearch">
              <template #icon>
                <SearchOutlined />
              </template>
              查询
            </a-button>
            <a-button @click="resetQuery">
              <template #icon>
                <ReloadOutlined />
              </template>
              重置
            </a-button>
          </a-button-group>
        </a-col>
      </a-row>
    </a-form>
  </a-card>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="query-table-wrapper">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <!-- <a-button @click="onExport" type="primary" v-privilege="'commission:driver:export'">
          <template #icon>
            <ExportOutlined />
          </template>
          导出
        </a-button> -->
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.GOODS" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <div class="table-wrapper">
      <a-table size="small" :dataSource="tableData" :columns="columns" bordered :scroll="{ x: 'max-content', y: tableScrollY }" :pagination="false" :showSorterTooltip="false" :loading="tableLoading" :row-selection="{}" @expand="onExpand">
        <template #bodyCell="{ text, record, column }">
          <template v-if="column.dataIndex === 'name'">
            <template v-if="record.level === expandLevel.ORDER.value">
              <div class="order-name">
                <CopyText :text="text">
                  <a class="order-no" @click="detail(record)" :style="{ color: record.is_account === 2 ? 'green' : 'red' }">{{ text }}</a>
                </CopyText>
                <div class="order-tag">
                  <a-tag color="#87d068" v-if="record.order_type === 1">销售</a-tag>
                  <a-tag color="#108ee9" v-if="record.order_type === 2">退货</a-tag>
                  <a-tag color="#2db7f5" v-if="record.order_type === 3">换货</a-tag>
                  <a-tag color="#2db166" v-if="record.order_type === 4">订货</a-tag>
                  <a-tag color="#1667f5" v-if="record.order_type === 5">订退</a-tag>
                  <a-tag color="#f50" v-if="record.is_abnormal === 2">异常</a-tag>
                </div>
              </div>
              <div>
                {{ record.store_name }}
              </div>
            </template>
          </template>
          <template v-if="column.dataIndex === 'comission'">
            <span>{{ Number(text).toFixed(2) }}</span>
          </template>
          <template v-if="column.dataIndex === 'order_amount'">
            <span>{{ Number(text).toFixed(2) }}</span>
          </template>
        </template>
      </a-table>
    </div>

    <DriverDetailsModal ref="detailRef" />
  </a-card>
</template>
<script setup lang="ts">
import _ from 'lodash'
import CustomRangePicker from '@/components/business/custom-range-picker/index.vue'
import Select from '@/components/business/select/index.vue'
import DriverDetailsModal from './components/driver-details-modal.vue'
import { commissionApi } from '@/api/business/finance/commission-api'
import TableOperator from '@/components/support/table-operator/index.vue'
import { useQuery } from '@/hooks/web/use-query-hook'
import { TIME_RANGE_PRESETS } from '@/constants/system/common-const'
import { TABLE_ID_CONST } from '@/constants/support/table-id-const'
import { useResize } from '@/hooks/web/use-resize-hook'
// ----------------------------- 计算表格高度 -----------------------------
const { tableScrollY } = useResize({ pagination: false })

// ---------------------------- 表格列 ----------------------------
const columns = ref([
  {
    title: '',
    dataIndex: 'expand',
    width: 30
  },
  {
    title: '司机',
    dataIndex: 'name',
    width: 320
  },
  {
    title: '提成金额',
    dataIndex: 'comission'
  },
  {
    title: '配送订单',
    dataIndex: 'order_num'
  },
  {
    title: '配送数量',
    dataIndex: 'goods_num'
  },
  {
    title: '订单金额',
    dataIndex: 'order_amount'
  }
])

// ---------------------------- 查询数据表单和方法 ----------------------------

// 定义折叠层级
const expandLevel = {
  PERSON: {
    value: 1,
    prefix: 'person_'
  },
  DATE: {
    value: 2,
    prefix: 'date_'
  },
  ORDER: {
    value: 3,
    prefix: 'order_'
  }
}

function transformData(data) {
  return data.map((person) => {
    const personNode = {
      ...person,
      name: person.driver_name,
      key: `${expandLevel.PERSON.prefix}${person.id}`,
      level: expandLevel.PERSON.value,
      children: Array.isArray(person.children)
        ? person.children.map((dateItem) => {
            const dateNode = {
              ...dateItem,
              name: dateItem.date,
              key: `${expandLevel.DATE.prefix}${dateItem.date}`,
              p_key: `${expandLevel.PERSON.prefix}${dateItem.date}`,
              level: expandLevel.DATE.value,
              children: Array.isArray(dateItem.children)
                ? dateItem.children.map((orderItem) => ({
                    ...orderItem,
                    name: orderItem.order_no, // 添加 name 字段
                    key: `${expandLevel.ORDER.prefix}${orderItem.order_no}`,
                    p_key: `${expandLevel.DATE.prefix}${orderItem.order_no}`,
                    level: expandLevel.ORDER.value
                  }))
                : []
            }
            return dateNode
          })
        : []
    }
    return personNode
  })
}

const { queryForm, queryData, tableData, tableLoading, resetQuery, onSearch } = useQuery({
  fetchDataApi: async ({ filter }) => {
    const data = { ...filter }
    const res = await commissionApi.queryList({ ...data })
    const result = transformData(res.data)
    return {
      list: result,
      total: 0
    }
  },
  queryFormFilter: {
    driver_id: null,
    create_time: TIME_RANGE_PRESETS.find((item) => item.key === 'today')?.value
  },
  queryFormOp: {}
})

// 展开行
function onExpand(expanded: boolean, record: any) {
  // 如果是折叠
  if (!expanded) return
  // 如果是展开
  if (record.children?.length > 0 || record.level === expandLevel.ORDER.value) return
}

onMounted(queryData)

// 选择表格行
const selectedRowKeyList = ref<number[]>([])

function onSelectChange(selectedRowKeys: number[]) {
  selectedRowKeyList.value = selectedRowKeys
}

// 详情
const detailRef = ref()
function detail(record) {
  detailRef.value.showDrawer(record)
}

// ------------------------------- 导出和导入 ---------------------------------
// 导出
function onExport() {
  const data = {
    driver_id: queryForm.value.driver_id,
    create_time: queryForm.value.create_time
  }
  commissionApi.exportXlsx(data)
}
</script>
<style lang="less" scoped>
.order-name {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.order-no {
  width: 225px;
}
.order-tag {
  flex: auto;
  display: flex;
  justify-content: start;
  align-items: center;
  gap: 4px;
}
</style>
